package com.ruoyi.web.controller.operate;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysMessage;
import com.ruoyi.system.domain.SysReply;
import com.ruoyi.system.service.ISysMessageService;
import com.ruoyi.system.service.ISysReplyService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 留言 信息操作处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/operate/message")
public class MessageController extends BaseController
{
    @Autowired
    private ISysMessageService messageService;

    @Autowired
    private ISysReplyService replyService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 获取留言列表
     */
    @PreAuthorize("@ss.hasPermi('operate:message:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysMessage message)
    {
        startPage();
        List<SysMessage> list = messageService.selectMessageList(message);
        if(CollectionUtil.isNotEmpty(list)){
            list.stream().forEach(sysMessage -> {
                String createBy = sysMessage.getCreateBy();
                if(StringUtils.isNotEmpty(createBy)){
                    SysUser sysUser = sysUserService.selectUserById(Long.parseLong(createBy));
                    if(sysUser != null){
                        sysMessage.setCreateBy(sysUser.getNickName());
                    }
                }

                Long id = sysMessage.getId();
                SysReply query = new SysReply();
                query.setDelFlag("0");
                query.setMessageId(id);
                List<SysReply> replyList = replyService.selectReplyList(query);
                if(CollectionUtil.isNotEmpty(replyList)){
                    sysMessage.setReplyTime(replyList.get(0).getReplyTime());
                }
            });
        }
        return getDataTable(list);
    }

    /**
     * 根据留言编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('operate:message:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return success(messageService.selectMessageById(id));
    }

    /**
     * 新增留言
     */
    @PreAuthorize("@ss.hasPermi('operate:message:add')")
    @Log(title = "留言", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysMessage message)
    {
        message.setCreateBy(String.valueOf(getUserId()));
        return toAjax(messageService.insertMessage(message));
    }

    /**
     * 修改留言
     */
    @PreAuthorize("@ss.hasPermi('operate:message:edit')")
    @Log(title = "留言", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysMessage message)
    {
        message.setUpdateBy(String.valueOf(getUserId()));
        return toAjax(messageService.updateMessage(message));
    }

    /**
     * 删除留言
     */
    @PreAuthorize("@ss.hasPermi('operate:message:remove')")
    @Log(title = "留言", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(messageService.deleteMessageByIds(ids));
    }


    @PreAuthorize("@ss.hasPermi('operate:message:reply')")
    @Log(title = "回复", businessType = BusinessType.REPLY)
    @PutMapping("/reply")
    public AjaxResult reply(@Validated @RequestBody SysReply reply)
    {
        LoginUser loginUser = getLoginUser();//获取当前登录信息
        SysMessage sysMessage = new SysMessage();
        try{
            if(loginUser != null){
                SysUser sysUser = loginUser.getUser();
                String isRegister = "";
                if(sysUser != null){
                    isRegister = sysUser.getIsRegister() == null? "0":sysUser.getIsRegister() ;//是否注册 1已注册，0未注册
                    if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("1")){//注册，则代表用户
                        reply.setReplyType("2");
                        sysMessage.setMessageStatus("1");//改成待回复
                    }else if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("0")){ //未注册，代表后台
                        reply.setReplyType("1");
                        sysMessage.setMessageStatus("2");//改成待关闭
                        messageService.replyMessage(reply);
                    }
                    reply.setCreateBy(String.valueOf(sysUser.getUserId()));

                    sysMessage.setId(reply.getMessageId());
                    sysMessage.setUpdateBy(String.valueOf(sysUser.getUserId()));
                    messageService.updateMessage(sysMessage);
                }
                replyService.insertReply(reply);
                return AjaxResult.success();
            }
        }catch (Exception e){
            return AjaxResult.error();
        }
        return null;
    }



    //邮件通知

    /**
     * 结束留言
     */
    @PreAuthorize("@ss.hasPermi('operate:message:end')")
    @Log(title = "留言", businessType = BusinessType.END)
    @GetMapping("end/{id}")
    public AjaxResult end(@PathVariable Long id)
    {
        return toAjax(messageService.endMessageById(id));
    }

}
